package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {
    private Socket socket;
    private String method;
    private String uri;
    private String protocol;
    private Map<String , String> headers = new HashMap<>();
    private String requestURI;
    private String queryString;
    private Map<String , String> parameters = new HashMap<>();
    public HttpServletRequest(Socket socket) throws IOException, EmptyRequestException {
        this.socket = socket;
        parseRequestLine();
        parseHeaders();
        parseContent();
    }

    private void parseRequestLine() throws IOException, EmptyRequestException {
        String line = readLine();
        System.out.println("请求行："+line);

        if (line==null){
            throw new EmptyRequestException();
        }

        String[] array = line.split("\\s");

        method = array[0];
        uri = array[1];
        protocol = array[2];

        parseURI();

        System.out.println("请求方式:"+method);
        System.out.println("请求路径:"+uri);
        System.out.println("协议版本:"+protocol);
    }

    private void parseURI(){
        String[] array = uri.split("\\?");
        requestURI = array[0];
        if (array.length>1){
            queryString = array[1];
        }
        parseParameter(queryString);

    }

    private void parseHeaders() throws IOException {
        String line;
        while (!(line = readLine()).isEmpty()){
            String[] array = line.split(":\\s");
            headers.put(array[0],array[1]);
            System.out.println("消息头:"+line);
        }
        System.out.println("消息头解析完毕");
    }

    private void parseContent() throws IOException {
        if ("post".equalsIgnoreCase(method)){
            if (headers.containsKey("Content-Length")){
                int contentLength = Integer.parseInt(
                        headers.get("Content-Length")
                );
                byte[] data = new byte[contentLength];
                InputStream in = socket.getInputStream();
                in.read(data);
                if (headers.containsKey("Content-Type")){
                    String contentType = headers.get("Content-Type");
                    if ("application/x-www-form-urlencoded".equals(contentType)){
                        String line = new String(data, StandardCharsets.ISO_8859_1);
                        parseParameter(line);
                    }
                }
            }
        }
    }

    private void parseParameter(String line){
        try {
            line = URLDecoder.decode(line,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String[] array = line.split("&");
        for (String data : array) {
            String[] arrays = data.split("=");
            parameters.put(arrays[0],arrays.length>1?arrays[1]:null);
        }
    }

    private String readLine() throws IOException {
        int d;
        StringBuilder builder = new StringBuilder();
        InputStream in = socket.getInputStream();
        char pre = 'a' , cur = 'a';
        while ((d = in.read())!=-1){
            pre = (char)d;
            if (cur==13&&pre==10){
                break;
            }
            builder.append(pre);
            cur = pre;
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeader(String name){
        return headers.get(name);
    }

    public String getRequestURI() {
        return requestURI;
    }

    public String getQueryString() {
        return queryString;
    }

    public String getParameter(String name){
        return parameters.get(name);
    }
}
